package com.resource.provider.util;


import com.auth.dto.auth.CommonAuthResponse;
import com.auth.dto.auth.GetAppPrivilegeRequest;
import com.auth.dto.auth.GetAppPrivilegeResponse;
import com.auth.dto.auth.GetServiceAuthRequest;
import com.auth.dto.common.Result;
import com.resource.provider.config.RedisUtil;
import com.resource.provider.exception.PermissionException;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;


/**
 * Created by adminchen on 17/4/11.
 * <p>
 * 5.9 by Rickon
 * 优化缓存逻辑
 */
@Component
public class TokenUtil {
    private static Logger logger = LoggerFactory.getLogger(TokenUtil.class);
    private static final String CORP_UUID = "a8c58297436f433787725a94f780a3c9";
    private static final String URL;
    private static final String SERVICE_UUID;
    private static final String SERVICE_SECRET;
    private static final String PREFIXION;
    private static final Long EXPIRE_TIME = 30L;
    private static final String ON_OFF;


    static {
        SERVICE_UUID = PropsUtil.getNoE("serviceUuid");
        SERVICE_SECRET = PropsUtil.getNoE("serviceSecret");
        URL = PropsUtil.getNoE("url");
        PREFIXION = PropsUtil.getNoE("prefixion");
        ON_OFF = PropsUtil.getNoE("on_off");
    }

    private final static long TIMESTAMP = System.currentTimeMillis() / 1000;


    private static TokenUtil tokenUtil;

    @Autowired
    private RedisUtil redisUtil;


    @PostConstruct
    public void init() {
        tokenUtil = this;
//        tokenUtil.authService = this.authService;
        tokenUtil.redisUtil = this.redisUtil;
        //tokenUtil.request = this.request;


    }

    /**
     * 获取微服务token RPC 调用
     *
     * @return json对象
     */
    public static JSONObject getServiceTokenRPC() {
        String signature = Md5Util.md5(SERVICE_UUID + TIMESTAMP + SERVICE_SECRET);
        //创建鉴权对象
        GetServiceAuthRequest request = new GetServiceAuthRequest();
        request.setSignature(signature);
        request.setTimestamp(TIMESTAMP);
        request.setServiceUuid(SERVICE_UUID);

        String url = "v1/authms/auth/service";
        String params = "service_uuid=" + SERVICE_UUID + "&timestamp=" + TIMESTAMP + "&signature=" + signature;
        JSONObject jsonObject = Https.sendPost(url, params);

        //获取返回值code
        int code = (int) jsonObject.get("code");
        //判断是否成功
        if (code != 0) {
            throw new PermissionException(code + "", jsonObject.getString("message"));
        }
        JSONObject json = JSONObject.fromObject(jsonObject.get("content"));
        json.put("serviceToken", json.get("accessToken"));
        return json;
    }


    /**
     * 获取租户id RPC 调用
     *
     * @param appToken 应用层token
     * @return 包含租户id对象
     */
    public static JSONObject getPrivilegeTokenRPC(String appToken) {
        //判断时候要开启鉴权
        if (!checkAuthONOFF()) {
            //先统一以这个默认的数据，看来是不能通过服务调用的方式了
            JSONObject json = new JSONObject();
            json.put("corpUuid", CORP_UUID);
            json.put("appUuid", "appUuid-dev");
            return json;
        }

        //获取微服务token
        String serviceToken = TokenUtil.getServiceTokenRPC().getString("serviceToken");
        GetAppPrivilegeRequest request = new GetAppPrivilegeRequest();
        request.setAppToken(appToken);
        request.setServiceToken(serviceToken);
        String url = "v1/authms/app/privilege";
        String params = "app_token=" + appToken + "&service_token=" + serviceToken;
        JSONObject jsonObject = Https.sendGet(url, params);
        Result<GetAppPrivilegeResponse> result = null;
        int code = (int) jsonObject.get("code");

        if (code != 0) {
            throw new PermissionException(code + "", jsonObject.get("message").toString());
        }
        JSONObject json = JSONObject.fromObject(jsonObject.get("content"));

        JSONObject corpJson = JSONObject.fromObject(json.getString("ext"));

        return corpJson;
    }



    /**
     * 迭代权限列表判定权限
     *
     * @param packageName
     * @param requestName
     * @param jsonArray
     */
    private static void checkPermissions(String packageName, String requestName, JSONArray jsonArray) {
        boolean privilegesBool = true;
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject objectTemp = (JSONObject) jsonArray.get(i);
            if (packageName.equals(objectTemp.getString("packageName"))
                    && requestName.equals(objectTemp.getString("requestName"))) {
                privilegesBool = false;
                break;
            }
        }
        if (privilegesBool) {
            logger.error("该微服务没有权限,请在ice操作台添加对应接口相关信息:\n接口list:" + jsonArray
                    + "\nownerPackageName:" + packageName
                    + "\nownerRequestName:" + requestName);

            throw new PermissionException("-1", "该微服务没有权限,请在ice操作台添加接口权限:\n"
                    + "\nownerPackageName:" + packageName
                    + "\nownerRequestName:" + requestName);
        }
    }

    /**
     * 检查是否开启鉴权
     *
     * @return true 开启鉴权 false 关闭鉴权
     */
    public static boolean checkAuthONOFF() {
        //String result = HttpUtil.sendGet(AUTH_ON_OFF_URL + "/on_off");
        //System.out.println("result:" + result);

        if (StringUtils.isBlank(ON_OFF)) {
            return true;
        }
        if ("on".equals(ON_OFF)) {
            return true;
        }
        if ("off".equals(ON_OFF)) {
            return false;
        }
        return true;
    }


    public static void main(String[] args) {
//        String signature = MD5Util.md5(SERVICE_UUID + TIMESTAMP + SERVICE_SECRET);
//        getServiceTokenRPC();
        getPrivilegeTokenRPC("b8fc74fba74a4dc59bf313bfecbbcf4b");
        //System.out.println("S
        // ERVICE_UUID:"+SERVICE_UUID);
        //System.out.println("signature:"+signature);
        //System.out.println("SERVICE_SECRET:"+SERVICE_SECRET);
        //System.out.println("TIMESTAMP:"+TIMESTAMP);
    }

    public static JSONObject getUUID() {
        String signature = Md5Util.md5(SERVICE_UUID + TIMESTAMP + SERVICE_SECRET);
        //System.out.println("SERVICE_UUID:"+SERVICE_UUID);
        //System.out.println("signature:"+signature);
        //System.out.println("SERVICE_SECRET:"+SERVICE_SECRET);
        //System.out.println("TIMESTAMP:"+TIMESTAMP);
        JSONObject json = new JSONObject();
        json.put("SERVICE_UUID", SERVICE_UUID);
        json.put("signature", signature);
        json.put("TIMESTAMP", TIMESTAMP);
        return json;
    }

}